<?php

chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir("../");
$path3 = getcwd();
chdir(dirname(__FILE__));
#debug($path3 , $path2);
include_once $path3."/lib/core.class.php";



class SettingsPlugin extends IPlugin 
{
    function SettingsPlugin($parent = null)
    {
        IPlugin::IPlugin($parent);
        $this->tplfolder = dirname(__FILE__)."/tpl";
    }
    
    function getPluginTag() { return "settings"; }
    function getPluginName() { return "Settings Plugin"; }
    function getPluginVersion() { return "1.0.0"; }
    
    function getProperty($p = null)
    {
        if(null == $p)
        {
            return array("MenuBlockTitle", "MenuTitle");
        }
        $result = "";
        switch ($p)
        {
            case "MenuBlockTitle": { return "Settings"; } break;
            case "MenuTitle" : { return "SiteSetup"; } break;
        }
        return $result;
    }

    // ----------------------------------------------------------------------------------
    // --- [ Handling all actions ] -----------------------------------------------------
    // ----------------------------------------------------------------------------------

    function doAction($params)
    {
        if(null != ($result = IPlugin::doAction($params)))
        {
            return $result;
        }

        switch ($_POST["action"]) {
            case "searchsetup": {
                    unset($_POST['action']);
                $core = &getCoreInstance();
                $db = $core->getProperty("db");
                
                if (is_numeric($_POST['s_rows']) and $_POST['s_rows'] > 0 and is_numeric($_POST['s_cols']) and $_POST['s_cols'] > 0){
                            $r = $_POST['s_rows'];
                            $c = $_POST['s_cols'];
                    $db->Exec("delete from settings where s_key = 's_rows' or s_key = 's_cols'");
                    $db->Exec("insert into settings(s_key,s_value) values ('s_rows','{$r}')");
                    $db->Exec("insert into settings(s_key,s_value) values ('s_cols','{$c}')");
                }

            } break;


            case "doUploadHeader": {
                $core = &getCoreInstance();
                $db = $core->getProperty("db");

            $banner_path = "/img/r_banner.png";
                                 
            @uploadFile('r_banner', $banner_path);

            } break;

            case "doUploadCenterHeader": {
                $core = &getCoreInstance();
                $db = $core->getProperty("db");

            $banner_path = "/img/banner_temp.jpg";
                                 
            @uploadFile('m_banner', $banner_path);

            } break;
        }

        
        // --- [ Check GET events ] -------------------------
        switch ($_GET["event"]) {
            case "delete": {
                $core = &getCoreInstance();
                $db = $core->getProperty("db");
                $db->Exec("delete from settings where `s_key` like '%{$_GET[key]}%'");
            } break;
        
            default:
                break;
        }

        // --- [ Check POST events ] ------------------------
        switch ($_POST["event"]) {
            case "doSettingSubmit": {

                $core = &getCoreInstance();
                $db = $core->getProperty("db");
                if($db->getOne("select count(*) from settings where `s_key` like '%{$_POST[key]}%'"))
                {
//                  $q = "update settings set s_value='".str2db($_POST["value"])."' where `s_key` like '%{$_POST[key]}%'";
                    $db->Exec("update settings set s_value='".str2db($_POST["value"])."' where `s_key` like '%{$_POST[key]}%'");
                }
                else
                {
//                  debug("insert");
                    $db->Exec("insert into settings(`s_key`, `s_value`) values('".str2db($_POST["key"])."', '".str2db($_POST["value"])."')");
                }
            } break;

            default:
                break;
        }

        $core = &getCoreInstance();
        return true;
    }


    // ----------------------------------------------------------------------------------
    // --- [ Render pages ] -------------------------------------------------------------
    // ----------------------------------------------------------------------------------

    function Render($params)
    {
        global $_G;
        if(null != ($result = IPlugin::Render($params)))
        {
            return $result;
        }
        
        $core = &getCoreInstance();
        $db = $core->getProperty("db");
        $framework = $core->getProperty("framework");
        $render = $framework->smarty;

        $page = "";

        switch ($_G["page"]) {
            case "edit": {
                $page = $this->renderSettingsEditPage($core, $render, $db);
            } break;
            case "clear_rating": {
                $page = $this->renderSettingsPage($core, $render, $db);
                $db->Exec("update catalog set rating = 0");
            } break;

            default:
                $page = $this->renderSettingsPage($core, $render, $db);
                break;
        }

        return $render->fetch("file:".$this->tplfolder."/".$page);
    }
    
    
    // ----------------------------------------------------------------------------------
    // --- [ Generate Customers List ] --------------------------------------------------
    // ----------------------------------------------------------------------------------

    function cb_renderSettings($data)
    {
        static $iteration;
        $iteration++;
        $dt = array(
                array($iteration, "align=\"center\""),
                array($data["s_key"], ""),
                array(strlen($data["s_value"])>30 ? substr($data["s_value"], 0, 27)."..." : $data["s_value"], ""),
                array("<a href=\"?".$this->getURL()."&page=edit&key={$data[s_key]}\">edit</a>"
                    ."&nbsp;&nbsp;"
                    ."<a href=\"?".$this->getURL()."&event=delete&key={$data[s_key]}\">delete</a>"
                    , "align=\"center\"")
                );
        return $dt;
    }



    function renderSettingsPage(&$core, &$render, &$db)
    {
        $exclude = "'saleofthemonth', 'specialoffer', 'specialoffer_slogan'";

        $pg = &$core->getSnippet("paginator");
        $page = $ppg = 0;
        $params = array(
                    "cb_class" => &$this,
                    "cb_func" => cb_renderSettings,
                    "urlbase" => $this->getURL(),
                    "caption" => "Settings",
                    "emptymsg" => "No settings set yet",
                    "header" => array("#", "Key", "Value", "Action"),
                    "items" => "",
                    "source" => "sql", // -- sql, array
                    "sql_items" => "select * from settings where `s_key` not in ({$exclude})",
                    "sql_count" => "select count(*) from settings where `s_key` not in ({$exclude})",
                    "ippg" => 15, // -- items per page
                    "nppv" => 5, // -- number pages per view
                    "page" => &$page,
                    "ppg" => &$ppg,
                    );
        
            $render->assign("settings", $pg->Render($params));

        $s_rows = $db->getone("select s_value from settings where s_key = 's_rows'");
        $s_cols = $db->getone("select s_value from settings where s_key = 's_cols'");
        $render->assign("s_rows", $s_rows);
        $render->assign("s_cols", $s_cols);


        return "settings.tpl.php";
    }
    
    function renderSettingsEditPage(&$core, &$render, &$db)
    {
        $key = $_GET["key"];
        $z = $db->getAll("select * from settings where `s_key` like '%{$key}%' and '{$key}'<>''");
        if(count($z))
        {
            $z = $z[0];
        }
        $render->assign("kv", $z);

        return "settingsedit.tpl.php";
    }
};


?>